package dome1;

public class BinarySearchTree {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    public TreeNode root;

    //O(logN)
    public boolean search(int val) {
        TreeNode cur = root;
        while(cur!=null) {
            if(cur.val < val) {
                cur = cur.right;
            }else if(cur.val > val) {
                cur = cur.left;
            }else {
                return true;
            }
        }
        return false;
    }

    //O(logN)
    public void insert(int val) {
        TreeNode node = new TreeNode(val);
        if(root == null) {
            root = node;
            return;
        }
        TreeNode parent = null;
        TreeNode cur = root;
        while(cur!=null) {
            parent = cur;
            if(val < cur.val) {
                cur = cur.left;
            }else if(val > cur.val) {
                cur = cur.right;
            }else {
                return;
            }
        }
        if(val < parent.val) {
            parent.left = node;
        }else {
            parent.right = node;
        }
    }
}
